import Taro from '@tarojs/taro'
import lovelornUser from '../api/lovelorn-user'
/**
 * @description 获取当前页url
 */
export const getCurrentPageUrl = () => {
  const pages = Taro.getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const url = currentPage.route
  return url
}

const loginThird = async (code, path) => {
  const result = await lovelornUser.action.login({
    code,
  })
  console.error(result, 'pagetologin')
  console.error(path, 'pagetologinpath')
  if (result && result.checkFlag) {
    Taro.setStorage({
      key: 'isLogin',
      data: true,
    })
    Taro.setStorage({
      key: 'loginVO',
      data: result.loginVO,
    })
    Taro.setStorage({
      key: 'openId',
      data: result.openId,
    })
    console.warn(`将跳转至${path}页面`)
    if (path) {
      if (path.indexOf('Home') > -1 || path.indexOf('cart') > -1 || path.indexOf('mine') > -1) {
        Taro.switchTab({
          url: `/${path}`,
        })
      } else {
        Taro.redirectTo({
          url: `/${path}`,
        })
      }
    } else {
      Taro.redirectTo({
        url: `/pages/Home/index`,
      })
    }
  } else {
    Taro.setStorage({
      key: 'isLogin',
      data: false,
    })
    Taro.navigateTo({
      url: `/pages/userLogin/index?path=${path}`,
    })
  }
}

export const loginWx = (path) => {
  return new Promise((resolve, reject) => {
    Taro.login({
      success: (res) => {
        resolve(loginThird(res.code, path))
      },
      fail: (error) => {
        console.log(error, 'error')
        Taro.showToast({
          title: '微信登录失败',
        })
      },
    })
  })
}

export const pageToLogin = () => {
  const path = getCurrentPageUrl()
  console.error(path, 'sss')
  Taro.redirectTo({
    url: `/pages/userLogin/index?path=${path}`,
  })
}
